<?php
class CommandesController extends AppController {
    public $helpers = array('Html', 'Form');
    public $components = array('RequestHandler');

    public function index() {

    	$this->layout = 'pharmarket';
    	$this->loadModel('Commande');
    	$commandes = $this->Commande->find('all');
        $this->set('commandes', $commandes);
    }

    public function edit($id){
    	if ($this->request->is(array('post', 'put'))) {
        	$this->Commande->id = $id;
	        if ($this->Commande->save($this->request->data)) {
	            return $this->redirect(array('action' => 'index'));
	        }
    	}

    	$this->Commande->recursive = 3;
    	$conditions = array('conditions' => array('Commande.id = ' => $id));
    	$commande = $this->Commande->find('all', $conditions);
    	$produits = [];
    	$prixTotal = 0;
    	for($i = 0; $i < sizeof($commande[0]['Row']); $i++){
    		$produits[$i]["id"] = $commande[0]['Row'][$i]["product_id"];
    		$produits[$i]["quantite"] = $commande[0]['Row'][$i]["quantite"];
    		$produits[$i]["prix"] = $commande[0]['Row'][$i]["Product"]["prix"];
    		$produits[$i]["nom"] = $commande[0]['Row'][$i]["Product"]["nom"];
    		$prixTotal += $produits[$i]["quantite"] * $produits[$i]["prix"];
    	}

    	$this->set('commande', $commande);
    	$this->set('produits', $produits);
    	$this->set('prixTotal', $prixTotal);

    	$this->layout = 'pharmarket';
    }

    public function ouvertes(){
    	$conditions = array('conditions' => array('Commande.etat_id = ' => 1));
    	$commandes = $this->Commande->find('all', $conditions);
        $this->set('commandes', $commandes);
        $this->layout = 'pharmarket';
    }

    public function encours(){
    	$conditions = array('conditions' => array('Commande.etat_id = ' => 2));
    	$commandes = $this->Commande->find('all', $conditions);
        $this->set('commandes', $commandes);
        $this->layout = 'pharmarket';
    }

    public function termines(){
    	$conditions = array('conditions' => array('Commande.etat_id = ' => 3));
    	$commandes = $this->Commande->find('all', $conditions);
        $this->set('commandes', $commandes);
        $this->layout = 'pharmarket';
    }
}
